var express = require('express');
var router = express.Router();
let jwt = require("jsonwebtoken");
let userService = require("../service/userServive")
let typeService = require("../service/typeService")
let typeMenuService = require("../service/typeMenuService");
let typeRouterService = require("../service/typeRouterService");

let projectService = require("../service/projectService")
/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.get("/list", async (req, res, next) => {
  let result = await userService.userQuery({});

  res.json({
    code: 200,
    data: result
  })

})

//查询自己的新增项目
router.get("/query", (req, res, next) => {
  let token = req.headers.token;//取出用户信息

  jwt.verify(token, "abc", async (err, info) => {
    if (!err) {
      let userid = info.id;

      let result = await projectService.query({ userid });
      // let name = await userService.query({ userid });
      res.json({
        code: 200,
        msg: "查询成功",
        data: result,
        // name:name
      })
    } else {
      res.json({
        code: 203,
        msg: "token过期 请重新登录"
      })
    }

  })

})


// // 项目经理查询项目渲染
// router.get("/managerquery", (req, res, next) => {
//   let token = req.headers.token;//取出用户信息
//   jwt.verify(token, "abc", async (err, info) => {
//     if (!err) {
//       let userid = info.id;
//       let result = await projectService.query({ userid });
//       res.json({
//         code: 200,
//         msg: "查询成功",
//         data: result,
//       })
//     } else {
//       res.json({
//         code: 203,
//         msg: "token过期 请重新登录"
//       })
//     }

//   })

// })


// 列表查询
router.get('/Allquery', (req, res, next) => {
  let { pageindex = 1, pageNum = 5 } = req.query;
  let token = req.headers.token;//取出用户信息

  jwt.verify(token, "abc", async (err, info) => {
    if (!err) {
      let params = {}
      if (info.type == 1) {
        params.userid = info.id
      }
      let result = await projectService.query(params, (pageindex - 1) * pageNum, pageNum * 1)
      let total = await projectService.totalquery(params)

      res.json({
        code: 200,
        msg: "查询成功",
        data: result,
        total,
      })

    } else {
      res.json({
        code: 200,
        msg: "token过期，请重新登录",
      })
    }
  })

})


router.post('/add', async (req, res, next) => {
  let { userid, project, projectname, requirement, start, extend, type = 0 } = req.body
  let params = { project, projectname, requirement, start, extend, type }

  jwt.verify(req.headers.token, 'abc', async (err, info) => {
    if (!err) {
      if (userid && info.type==0) {
          params.userid = userid
          let userList = await userService.query({ _id: userid })
          params.username = userList[0].username
      }else{
        if(info.type!=0){
          params.userid = info.id
          params.username = info.username
          params.type = 1
        }
      }
      
      // 检查项目名是否有重复
      let projectInfo = await projectService.query({project})
      if(projectInfo.length){
        res.send({
          code: 203,
          msg: "添加失败,项目名重复",
        })
      }else{
        let result = await projectService.add(params);
        if (result.length) {
          res.send({
            code: 200,
            msg: "添加成功",
            data: result
          })
        } else {
          res.send({
            code: 203,
            msg: "添加失败",
          })
        }
      }

    } else {
      res.send({
        code: 203,
        msg: "token过期，请重新登录",
      })
    }

  })

})


router.get("/group", (req, res, next) => {
  let token = req.headers.token;
  jwt.verify(token, "abc", async (err, info) => {
    if (!err) {
      let pid = info.id; //老师的编号 也就是登录人的编号
      let result = await userService.query({ pid });
      let studentList = result.map((item) => item._id + ""); //这个老师的所有学生的编号
      let key = req.query.key;//分组的关键字
      let result2 = await projectService.group(
        { userid: { $in: studentList } },
        key
      );

      res.json({
        code: 200,
        msg: "分组统计",
        data: result2,
      });
    } else {
      res.json({
        code: 203,
        msg: "token异常",
        data: err,
      });
    }
  });
});


router.delete("/del", async (req, res, next) => {
  let {
    _id
  } = req.body;
  let result = await projectService.del({
    _id
  });
  if (result.deletedCount) {
    res.json({
      code: 200,
      msg: "删除成功"
    })

  } else {
    res.json({
      code: 203,
      msg: "删除失败"
    })
  }
})


// 更新
router.patch('/update', async (req, res, next) => {
  let { userid, type, _id,end } = req.body
  let userInfo = await userService.query({ _id: userid })
  let params = {type, userid, username: userInfo[0].username}
  if(end){
    params.end = end
  }
  let result = await projectService.update({ _id }, { $set: params });
  let projectList = await projectService.query({ _id })

  if (result.nModified) {
    res.send({
      code: 200,
      msg: "编辑成功",
      data: projectList
    })
  } else {
    res.send({
      code: 203,
      msg: "编辑失败,请重试",
    })
  }
})


module.exports = router;